<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="工程名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入工程名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工程地址" prop="projectAddress">
        <el-input v-model="queryParams.projectAddress" placeholder="请输入工程地址" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="建设单位" prop="constructionUnit">
        <el-input v-model="queryParams.constructionUnit" placeholder="请输入建设单位" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="总包单位" prop="generalContractor">
        <el-input v-model="queryParams.generalContractor" placeholder="请输入总包单位" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同工期" prop="contractPeriod">
        <el-input v-model="queryParams.contractPeriod" placeholder="请输入合同工期" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="承包方式" prop="contractingMethod">
        <el-input v-model="queryParams.contractingMethod" placeholder="请输入承包方式" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合同造价" prop="contractCost">
        <el-input v-model="queryParams.contractCost" placeholder="请输入合同造价" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['production:projectContractInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['production:projectContractInfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['production:projectContractInfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['production:projectContractInfo:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload" size="mini" @click="handleFileUpload">文件上传</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectContractInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="工程名称" width="120" align="center" prop="projectName">
        <template slot-scope="scope">
          <el-tooltip placement="top" :disabled="!scope.row.projectName || scope.row.projectName.length <= 15"
            popper-class="contract-tooltip">
            <div slot="content" class="tooltip-content">{{ scope.row.projectName }}</div>
            <div class="ellipsis-text">{{ scope.row.projectName || '-' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="工程地址" align="center" prop="projectAddress" />
      <el-table-column label="建设单位" align="center" prop="constructionUnit" />
      <el-table-column label="总包单位" align="center" prop="generalContractor" />
      <el-table-column label="合同工期" align="center" prop="contractPeriod" />
      <el-table-column label="承包方式" align="center" prop="contractingMethod" />
      <el-table-column label="合同造价" align="center" prop="contractCost" />
      <el-table-column label="承包内容" width="120" align="center" prop="contractContent">
        <template slot-scope="scope">
          <el-tooltip placement="top" :disabled="!scope.row.contractContent || scope.row.contractContent.length <= 15"
            popper-class="contract-tooltip">
            <div slot="content" class="tooltip-content">{{ scope.row.contractContent }}</div>
            <div class="ellipsis-text">{{ scope.row.contractContent || '-' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['production:projectContractInfo:query']">详情</el-button>

          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['production:projectContractInfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['production:projectContractInfo:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleAssign(scope.row)"
            v-hasPermi="['production:projectContractInfo:allot']">分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改工程项目信息-合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工程名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入工程名称" />
        </el-form-item>
        <el-form-item label="工程地址" prop="projectAddress">
          <el-input v-model="form.projectAddress" placeholder="请输入工程地址" />
        </el-form-item>
        <el-form-item label="建设单位" prop="constructionUnit">
          <el-input v-model="form.constructionUnit" placeholder="请输入建设单位" />
        </el-form-item>
        <el-form-item label="总包单位" prop="generalContractor">
          <el-input v-model="form.generalContractor" placeholder="请输入总包单位" />
        </el-form-item>
        <el-form-item label="合同工期" prop="contractPeriod">
          <el-input v-model="form.contractPeriod" placeholder="请输入合同工期" />
        </el-form-item>
        <el-form-item label="承包方式" prop="contractingMethod">
          <el-input v-model="form.contractingMethod" placeholder="请输入承包方式" />
        </el-form-item>
        <el-form-item label="合同造价" prop="contractCost">
          <el-input v-model="form.contractCost" placeholder="请输入合同造价" />
        </el-form-item>
        <el-form-item label="承包内容" prop="contractContent">
          <!-- <editor v-model="form.contractContent" :min-height="192"/> -->
          <el-input v-model="form.contractContent" type="textarea" :rows="4" placeholder="请输入承包内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配人员" :visible.sync="assignDialogVisible" width="400px" append-to-body>
      <el-form>
        <!-- <el-form-item label="搜索用户">
          <el-input v-model="userSearchName" placeholder="请输入用户名" clearable @keyup.enter.native="handleUserSearch"
            style="width: 100%;">
            <template slot="append">
              <el-button icon="el-icon-search" @click="handleUserSearch"></el-button>
            </template>
          </el-input>
        </el-form-item> -->
        <el-form-item label="选择人员">
          <el-select v-model="selectedUsers" multiple filterable placeholder="请选择人员" style="width: 100%;">
            <el-option v-for="user in userList" :key="user.userId" :label="user.userName" :value="user.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssign">确 定</el-button>
        <el-button @click="assignDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 工程项目信息详情对话框 -->
    <el-dialog :visible.sync="detailOpen" width="900px" :show-close="true" append-to-body class="daily-detail-dialog">
      <div class="daily-detail-title">工程项目信息详情</div>
      <div class="daily-section-title">基本信息</div>
      <!-- 工程名称单独一行显示 -->
      <table class="daily-detail-table">
        <tr>
          <th class="left-align">工程名称</th>
          <td class="value">{{ detailForm.projectName }}</td>
        </tr>
      </table>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">工程地址</th>
              <td class="value">{{ detailForm.projectAddress }}</td>
            </tr>
            <tr>
              <th class="left-align">建设单位</th>
              <td class="value">{{ detailForm.constructionUnit }}</td>
            </tr>
            <tr>
              <th class="left-align">总包单位</th>
              <td class="value">{{ detailForm.generalContractor }}</td>
            </tr>
          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">合同工期</th>
              <td class="value">{{ detailForm.contractPeriod }}</td>
            </tr>
            <tr>
              <th class="left-align">承包方式</th>
              <td class="value">{{ detailForm.contractingMethod }}</td>
            </tr>
            <tr>
              <th class="left-align">合同造价</th>
              <td class="value">{{ detailForm.contractCost }}</td>
            </tr>
            <!-- <tr>
              <th class="left-align">创建时间</th>
              <td class="value">{{ detailForm.createTime }}</td>
            </tr> -->
          </table>
        </div>
      </div>
      <div class="daily-section-title">承包内容</div>
      <table class="daily-detail-table">
        <tr>
          <th class="center-bg">承包内容</th>
          <td class="value">{{ detailForm.contractContent }}</td>
        </tr>
      </table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>

    <!-- 文件上传对话框 -->
    <el-dialog title="文件上传" :visible.sync="uploadDialogVisible" width="500px" append-to-body>
      <el-upload ref="upload" class="upload-demo" action="#" :on-preview="handlePreview" :on-remove="handleRemove"
        :on-change="handleFileChange" :file-list="fileList" :auto-upload="false" :limit="5" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">支持上传多个文件，单个文件大小不超过50MB</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload" :loading="uploadLoading">确 定</el-button>
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProjectContractInfo, getProjectContractInfo, delProjectContractInfo, addProjectContractInfo, updateProjectContractInfo, addPerson } from "@/api/production/projectContractInfo";
import { listUser } from "@/api/system/user";
import { listProjectMember } from "@/api/production/projectMember";
import { addFileCloud } from "@/api/production/projectFileInfo";
export default {
  name: "ProjectContractInfo",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工程项目信息-合同信息表格数据
      projectContractInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectAddress: null,
        constructionUnit: null,
        generalContractor: null,
        contractPeriod: null,
        contractingMethod: null,
        contractCost: null,
        contractContent: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "工程名称不能为空", trigger: "blur" }
        ],
        projectAddress: [
          { required: true, message: "工程地址不能为空", trigger: "blur" }
        ],
        constructionUnit: [
          { required: true, message: "建设单位不能为空", trigger: "blur" }
        ],
        generalContractor: [
          { required: true, message: "总包单位不能为空", trigger: "blur" }
        ],
        contractPeriod: [
          { required: true, message: "合同工期不能为空", trigger: "blur" }
        ],
        contractingMethod: [
          { required: true, message: "承包方式不能为空", trigger: "blur" }
        ],
        contractCost: [
          { required: true, message: "合同造价不能为空", trigger: "blur" }
        ],
        contractContent: [
          { required: true, message: "承包内容不能为空", trigger: "blur" }
        ],
      },
      assignDialogVisible: false,
      currentAssignProjectId: null,
      selectedUsers: [],
      userList: [],
      userSearchName: '',
      // 添加详情弹框相关变量
      detailOpen: false,
      detailForm: {},
      // 文件上传相关变量
      uploadDialogVisible: false,
      fileList: [],
      uploadLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 详情按钮操作 */
    handleView(row) {
      getProjectContractInfo(row.id).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 查询工程项目信息-合同信息列表 */
    getList() {
      this.loading = true;
      listProjectContractInfo(this.queryParams).then(response => {
        this.projectContractInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        projectAddress: null,
        constructionUnit: null,
        generalContractor: null,
        contractPeriod: null,
        contractingMethod: null,
        contractCost: null,
        contractContent: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工程项目信息-合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProjectContractInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工程项目信息-合同信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProjectContractInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProjectContractInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工程项目信息-合同信息编号为"' + ids + '"的数据项？').then(function () {
        return delProjectContractInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('production/projectContractInfo/export', {
        ...this.queryParams
      }, `projectContractInfo_${new Date().getTime()}.xlsx`)
    },
    handleAssign(row) {
      this.currentAssignProjectId = row.id;
      this.assignDialogVisible = true;
      this.selectedUsers = [];
      this.userSearchName = '';
      this.loadUserList(row.id);
    },
    loadUserList(projectId) {
      listUser({ pageNum: 1, pageSize: 500, userName: this.userSearchName, deptId: 4 }).then(res => {
        this.userList = res.rows || [];
        // 再查当前项目已分配人员
        listProjectMember({ projectId }).then(memberRes => {
          this.selectedUsers = (memberRes.rows || []).map(item => item.userId);
        });
      });
    },
    handleUserSearch() {
      if (!this.currentAssignProjectId) return;
      this.loadUserList(this.currentAssignProjectId);
    },
    submitAssign() {
      if (!this.currentAssignProjectId || this.selectedUsers.length === 0) {
        this.$modal.msgError("请选择人员");
        return;
      }
      addPerson({ projectId: this.currentAssignProjectId, userIds: this.selectedUsers.join(',') }).then(() => {
        this.assignDialogVisible = false;
        this.$modal.msgSuccess("分配成功");
      });
    },
    /** 文件上传按钮操作 */
    handleFileUpload() {
      this.uploadDialogVisible = true;
      this.fileList = [];
    },
    /** 文件列表变化 */
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    /** 移除文件 */
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    /** 预览文件 */
    handlePreview(file) {
      console.log(file);
    },
    /** 提交上传 */
    submitUpload() {
      if (!this.fileList || this.fileList.length === 0) {
        this.$modal.msgError("请选择要上传的文件");
        return;
      }
      this.uploadLoading = true;
      const uploadPromises = this.fileList.map(file => {
        return addFileCloud(file.raw);
      });
      Promise.all(uploadPromises).then(() => {
        this.$modal.msgSuccess("上传成功");
        this.uploadLoading = false;
        this.uploadDialogVisible = false;
        this.fileList = [];
      }).catch(error => {
        this.$modal.msgError("上传失败：" + (error.msg || error.message));
        this.uploadLoading = false;
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 28px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 36px;
  text-align: center;
  letter-spacing: 2px;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: none;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 120px;
  color: #6b7a90;
  background: none;
  font-weight: normal;
  text-align: right;
  vertical-align: top;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table tr:last-child td,
.daily-detail-table tr:last-child th {
  border-bottom: none;
}

.daily-detail-table th.left-align {
  text-align: center;
  padding-left: 0;
  padding-right: 0;
  background: #f7fafd;
}

.daily-detail-table th.center-bg {
  text-align: center;
  vertical-align: middle;
  background: #f7fafd;
  width: 180px;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }
}

.ellipsis-text {
  display: block;
  width: 100%;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  text-align: center;
  margin: 0 auto;
}

/* 自定义tooltip样式 */
.contract-tooltip {
  max-width: 200px !important;
  width: 200px !important;
}

.contract-tooltip .tooltip-content {
  word-break: break-word !important;
  white-space: pre-wrap !important;
  line-height: 1.5 !important;
  word-wrap: break-word !important;
  overflow-wrap: break-word !important;
  max-width: 200px !important;
  width: 200px !important;
}
</style>
